package avicit.bdp.dms.prm.rest;

import avicit.bdp.common.dto.PythonResourceDTO;
import avicit.bdp.common.dto.upload.ResumeUploadDto;
import avicit.bdp.common.service.service.FileCommonService;
import avicit.bdp.dms.prm.service.PythonResourceService;
import avicit.platform6.core.rest.msg.QueryRespBean;
import avicit.platform6.core.rest.msg.ResponseMsg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @金航数码科技有限责任公司
 * @作者：liyb
 * @邮箱：liyb@avic-digital.com
 * @创建时间：2021-04-27 14:55
 * @类说明：python包管理
 * @修改记录：
 */
@RestController
@RequestMapping("/api/bdp/dms/prm/pythonresource")
@Api(tags = "python包管理接口")
public class PythonResourceRest {

    private static final Logger logger = LoggerFactory.getLogger(PythonResourceRest.class);
    @Autowired
    private PythonResourceService pythonResService;
    @Autowired
    private FileCommonService fileCommonService;

    @ApiOperation(value = "查询python资源列表")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "名称", name = "name", dataType = "String"),
            @ApiImplicitParam(value = "状态", name = "status", dataType = "Int"),
            @ApiImplicitParam(value = "当前页", name = "pageNo", dataType = "Int"),
            @ApiImplicitParam(value = "每页大小", name = "pageSize", dataType = "Int")
    })
    @GetMapping("/getPythonResList")
    public ResponseMsg<QueryRespBean<PythonResourceDTO>> getPythonResList(@RequestParam(required = false) String name,
                                                                          @RequestParam(required = false) Integer status,
                                                                          @RequestParam(defaultValue = "1") Integer pageNo,
                                                                          @RequestParam(defaultValue = "10") Integer pageSize) throws Exception{
        ResponseMsg<QueryRespBean<PythonResourceDTO>> responseMsg = new ResponseMsg<>();
        QueryRespBean<PythonResourceDTO> queryRespBean = pythonResService.getPythonResList(name, status, pageNo, pageSize);
        responseMsg.setResponseBody(queryRespBean);
        return responseMsg;
    }

    @ApiOperation(value = "删除python资源")
    @DeleteMapping("/deletePythonRes")
    public ResponseMsg<Boolean> deletePythonRes(@RequestBody PythonResourceDTO pythonResourceDTO) {
        ResponseMsg<Boolean> responseMsg = new ResponseMsg<>();
        responseMsg.setResponseBody(pythonResService.deletePythonRes(pythonResourceDTO.getId()));
        return responseMsg;
    }

    @ApiOperation(value = "python包上传")
    @PostMapping("/uploadPythonRes")
    public ResponseMsg<String> uploadPythonRes(ResumeUploadDto resumeUploadDto,
                                               HttpServletResponse response) throws Exception{
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        long startTime = System.currentTimeMillis();
        resumeUploadDto.setHdfsPath("/dds/python");
        try {
            pythonResService.uploadPythonRes(resumeUploadDto);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            responseMsg.setErrorDesc(e.getMessage());
            logger.error(e.getMessage(), e);
        }

        long endTime = System.currentTimeMillis();
        logger.info("上传文件{}--{}/{}，开始时间：{}，结束时间：{}，耗时：{}", resumeUploadDto.getFile().getOriginalFilename(),
                resumeUploadDto.getChunk(), resumeUploadDto.getChunks(), startTime, endTime, endTime - startTime);

        return responseMsg;
    }

    @ApiOperation(value = "获取已经上传的分片信息")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "文件唯一标识", name = "fileMd5", dataType = "String" ,required = true),
            @ApiImplicitParam(value = "hdfsPath", name = "hdfsPath", dataType = "String"),
            @ApiImplicitParam(value = "文件名称", name = "fileName", dataType = "String" ,required = true)
    })
    @GetMapping("/uploadPythonRes")
    public ResponseMsg<Map<String, List<Integer>>> getUploadedChunkInfoList(
            @RequestParam String fileMd5,
            @RequestParam(required = false) String hdfsPath,
            @RequestParam String fileName) throws Exception {
        ResponseMsg<Map<String, List<Integer>>> responseMsg = new ResponseMsg<>();
        Long startTime = System.currentTimeMillis();
        hdfsPath = "/dds/python";
        responseMsg.setResponseBody(fileCommonService.getUploadedChunkInfos(fileMd5, hdfsPath, fileName));
        Long endTime = System.currentTimeMillis();
        logger.info("开始时间：{}，结束时间：{}，耗时：{}", startTime, endTime, endTime - startTime);
        return responseMsg;
    }

    @ApiOperation(value = "获取文件上传是否成功[成功，暂停，失败的话响应，否则等待]")
    @PostMapping("/mergeChunks")
    public ResponseMsg<Map<String, String>> mergeChunks(@RequestBody ResumeUploadDto resumeUploadDto) throws Exception {
        ResponseMsg<Map<String, String>> responseMsg = new ResponseMsg<>();
        resumeUploadDto.setHdfsPath("/dds/python");
        responseMsg.setResponseBody(pythonResService.mergeChunks(resumeUploadDto));
        return responseMsg;
    }

    @ApiOperation(value = "删除文件上传")
    @DeleteMapping("/deleteFileUpload")
    public ResponseMsg<Boolean> deleteFileUpload(@RequestBody ResumeUploadDto resumeUploadDto) throws Exception {
        ResponseMsg<Boolean> responseMsg = new ResponseMsg<>();
        responseMsg.setResponseBody(fileCommonService.deleteFileUpload(resumeUploadDto.getFileMd5(), resumeUploadDto.getHdfsPath(),
                resumeUploadDto.getFileName()));
        return responseMsg;
    }

    @ApiOperation(value = "查看Python资源详情")
    @ApiImplicitParam(value = "id", name = "id", dataType = "String" ,required = true)
    @GetMapping("/getPythonResById")
    public ResponseMsg<PythonResourceDTO> getPythonResById(@RequestParam String id) {
        ResponseMsg<PythonResourceDTO> responseMsg = new ResponseMsg<>();
        responseMsg.setResponseBody(pythonResService.getPythonResById(id));
        return responseMsg;
    }

    @GetMapping("/getUploadType")
    @ApiOperation(value = "获取上传类型")
    public ResponseMsg<Boolean> getUploadType() {
        ResponseMsg<Boolean> responseMsg = new ResponseMsg<>();
        responseMsg.setResponseBody(fileCommonService.getUploadType());
        return responseMsg;
    }

}
